import { ControlFlowCommandNames } from '@/popup/models/Command';

export function deriveCommandLevels(commandStack) {
    let level = 0;
    let levels = [];
    commandStack.forEach(function (command) {
        if (levelCommand[command.command]) {
            let result = levelCommand[command.command](command, level, levels);
            level = result.level;
            levels = result.levels;
        } else {
            let result = levelDefault(command, level, levels);
            levels = result.levels;
        }
    });
    return levels;
}

let levelCommand = {
    [ControlFlowCommandNames.do]: levelBranchOpen,
    [ControlFlowCommandNames.else]: levelElse,
    [ControlFlowCommandNames.elseIf]: levelElse,
    [ControlFlowCommandNames.end]: levelBranchEnd,
    [ControlFlowCommandNames.forEach]: levelBranchOpen,
    [ControlFlowCommandNames.if]: levelBranchOpen,
    [ControlFlowCommandNames.repeatIf]: levelBranchEnd,
    [ControlFlowCommandNames.times]: levelBranchOpen,
    [ControlFlowCommandNames.while]: levelBranchOpen,
};

function levelDefault(_command, level, _levels) {
    let levels = [..._levels];
    levels.push(level);
    return { level, levels };
}

function levelBranchOpen(_command, level, _levels) {
    let levels = [..._levels];
    levels.push(level);
    level++;
    return { level, levels };
}

function levelBranchEnd(_command, level, _levels) {
    let levels = [..._levels];
    level--;
    levels.push(level);
    return { level, levels };
}

function levelElse(_command, level, _levels) {
    let levels = [..._levels];
    level--;
    levels.push(level);
    level++;
    return { level, levels };
}
